{% extends "base.html" %}

{% block title %}Node监控{% endblock %}

{% block head %}
{{ super() }}
{% endblock %}

{% block content %}
<!-- 页面头 -->
<section class="content-header">
  <!--头部标题-->
  <h1>
    Node监控
    <small id="title"></small>
  </h1>
  <!--面包屑-->
  <ol class="breadcrumb">
    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
    <li><a href="/blues/blues/clusterler/cluster">集群管理</a></li>
    <li class="active">Node监控</li>
  </ol>

</section>

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">
      <form class="form-inline" style="margin-bottom: 10px">
        <div class="form-group">
          <label for="selectTimeRange"> 选择时间范围 </label>
          <select class="form-control need-refresh-page" id="selectTimeRange" name="cluster_id" required>
            <option value="hour" selected>最近1小时</option>
            <option value="day">最近1天</option>
            <option value="week">最近1周</option>
          </select>
        </div>
      </form>
    </div>
  </div>


  <div class="row">

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">CPU使用率(%)</h3>

          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_cpu" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">CPU Load</h3>

          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_load" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">内存使用率(%)</h3>

          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_mem" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">磁盘使用率(%)</h3>
          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_disk" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">网卡入流量(kbps)</h3>
          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_net_in" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>

    <div class="col-md-6">
      <!-- AREA CHART -->
      <div class="box">
        <div class="box-header with-border">
          <h3 class="box-title">网卡出流量(kbps)</h3>
          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
        </div>
        <div class="box-body">
          <div id="box_net_out" style="height:250px"></div>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>


  </div>


</section>
<!-- /.页面内容 -->
{% endblock %}

{% block script %}
<script src="/static/js/echarts.min.js"></script>
<script type="text/javascript">

    var cluster_id = getQueryString('cluster_id')
    var instance = getQueryString('instance')
    var time_range = getQueryString('time_range')
    var query_str_cpu = `100-(avg by(instance) (rate(node_cpu_seconds_total{mode='idle',instance='${instance}'}[2m])) * 100)`
    var query_str_load = `node_load1{instance='${instance}'}`
    var query_str_mem = `(1-node_memory_MemAvailable_bytes{instance='${instance}'}/node_memory_MemTotal_bytes{instance='${instance}'})*100`
    var query_str_disk = encodeURIComponent(`max((node_filesystem_size_bytes{fstype=~'ext.?|xfs',instance='${instance}'}-node_filesystem_free_bytes{fstype=~'ext.?|xfs',instance='${instance}'})*100/(node_filesystem_avail_bytes{fstype=~'ext.?|xfs',instance='${instance}'}+(node_filesystem_size_bytes{fstype=~'ext.?|xfs',instance='${instance}'}-node_filesystem_free_bytes{fstype=~'ext.?|xfs',instance='${instance}'})))by(instance)`)
    // console.log(query_str_disk)
    var query_str_net_in = `rate(node_network_receive_bytes_total{instance='${instance}',device="eth0"}[2m])/1024`
    var query_str_net_out = `rate(node_network_transmit_bytes_total{instance='${instance}',device="eth0"}[2m])/1024`

    function timestamp2time(timestamp) {
        //直接用 new Date(时间戳) 格式转化获得当前时间
        var timestamp1 = new Date(timestamp * 1000);
        //再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
        dateString = timestamp1.toLocaleDateString().replace(/\//g, "-").substr(5) + "\n" + timestamp1.toTimeString().substr(0, 5)
        return dateString
    }

    // 检测选择变化，则重载页面
    $(".need-refresh-page").change(function () {
        console.log("need-refresh-page")
        let new_time_range = $('#selectTimeRange').val()
        location.href = location.pathname + `?cluster_id=${cluster_id}&instance=${instance}&time_range=${new_time_range}`
    })

    function getAndDrawPromData(query_str, domId) {
        $.ajax({
            url: `/api/v1/cluster/${cluster_id}/prom/query_range?time_range=${time_range}&query=${query_str}`,
            success: function (data) {
                drawPromData(domId, data)
            }
        })
    }

    function drawPromData(domId, response) {
        let date = [], data = [];
        if (response.status != 'success' || response.data.result.length == 0 || response.data.result[0].values.length == 0) {
            console.log(response)
            return
        }

        let raw_data = response.data.result[0].values
        for (let i = 0, len = raw_data.length; i < len; i++) {
            date.push(timestamp2time(raw_data[i][0]));
            data.push(parseFloat(raw_data[i][1]).toFixed(2));
        }
        // console.log(date)
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById(domId));
        // 指定图表的配置项和数据
        var option = {
            grid: {
                top: '3%',
                right: '2%',
                left: '2%',
                bottom: '5%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
            },
            xAxis: {
                type: 'category',
                data: date
            },
            yAxis: {
                type: 'value',
                // max: 100,
                splitLine: {
                    lineStyle: {
                        type: 'dashed'
                    }
                },
            },
            series: [
                {
                    // name: 'CPU使用率',
                    data: data,
                    // areaStyle: {normal: {}},
                    type: 'line',
                    smooth: false,
                    symbol: 'none',//去掉小圆点
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }

    $(function () {
        // 时间范围
        $('#selectTimeRange').val(time_range)
        // 标题
        let text = "节点：" + instance
        console.log(text)
        $('#title').text(text)

        getAndDrawPromData(query_str_cpu, 'box_cpu')
        getAndDrawPromData(query_str_load, 'box_load')
        getAndDrawPromData(query_str_mem, 'box_mem')
        getAndDrawPromData(query_str_disk, 'box_disk')
        getAndDrawPromData(query_str_net_in, 'box_net_in')
        getAndDrawPromData(query_str_net_out, 'box_net_out')


    })


</script>
{% endblock %}